package com.wqd.es;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wqd.es.mapper.ApArticleMapper;
import com.wqd.es.pojo.SearchArticleVo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@SpringBootTest
@RunWith(SpringRunner.class)
public class ApArticleTest2 {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private RestHighLevelClient client;

    /**
     * 注意：数据量的导入，如果数据量过大，需要分页导入
     * @throws Exception
     */
    @Test
    public void init() throws Exception {
        //获取数据库表的数据
        List<SearchArticleVo> articleList = apArticleMapper.loadArticleList();
        //导入es
        BulkRequest bulkRequest = new BulkRequest();
        //索引请求对象
        for (SearchArticleVo searchArticleVo : articleList) {
            //封装数据
            IndexRequest indexRequest = new IndexRequest("app_info_article").id(searchArticleVo.getId().toString());
            //添加suggestion数据
            List<String> suggestion = packingSuggestion(searchArticleVo);
            searchArticleVo.setSuggestion(suggestion);
            //指定数据源
            indexRequest.source(JSON.toJSONString(searchArticleVo),XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }

    /**
     * 封装suggestion方法
     * @param vo
     * @return
     */
    private List<String> packingSuggestion(SearchArticleVo vo) {
        List<String> list = new ArrayList<>();
        //解析内容
        String content = vo.getContent();
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        for (Map map : maps) {
            if(map.get("type").equals("text")){
                String value = (String) map.get("value");
                list.addAll(Arrays.asList(value.split(",")));
            }
        }
        //添加标题
        list.add(vo.getTitle());
        return list;
    }

}